<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="700px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" label-width="100px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="recordName" style="width:300px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc" style="width:300px;" ref="desc" :autosize="{ minRows: 4 }" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
        </el-form-item>
        <el-form-item :label="$t('URL地址')" prop="url">
          <el-input v-emoji v-model="url" style="width:300px;" ref="url" size='small' :placeholder="$t('完整host或host中的子串')"></el-input>
          <el-button type="success" @click="addUrl(url)" size="small" class="innerAddClick">{{$t('添加')}}</el-button>
        </el-form-item>
        <div style="margin-top:20px" class="avScrollbar">
          <el-table ref="multipleTable" size='mini' :data="urlList" border>
            <el-table-column prop="name" align='center' :label="$t('URL名称')" min-width="300">
            </el-table-column>
            <el-table-column align='center' width='100' fixed="right" :label="$t('操作')">
              <template slot-scope="scope">
                <el-button type="danger" plain size="mini" @click="delUrl(scope.row)" :ref="'del' + (scope.$index + 1)">{{$t('删除')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addUrlClass, editUrlClass } from '@/api/safe/url'
import { inputClass, texttextClass } from '@/utils/input-class.js'
export default {
  name: 'UrlDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        id: null,
        name: '',
        desc: '',
        url: ''
      },
      recordCopy: {
        id: null,
        name: '',
        desc: '',
        url: ''
      },
      url: '',
      urlList: [],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['recordName', 'url']
        const textdata = ['desc']
        inputClass(this.$refs, data)
        texttextClass(this.$refs, textdata)
      })
      if (data) {
        this.record = Object.assign(this.record, data)
        for (let item of data.url) {
          this.urlList.push({ name: item })
        }
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.urlList.length) {
            for (let index in this.urlList) {
              if (index === '0') {
                this.record.url = this.urlList[index].name
              } else {
                this.record.url += ',' + this.urlList[index].name
              }
            }
            if (this.record.id) {
              editUrlClass(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              addUrlClass(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            }
          } else {
            this.$message({
              message: this.$t('请至少添加一条数据'),
              type: 'error'
            })
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.url = ''
      this.urlList = []
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    addUrl (url) {
      if (url) {
        this.urlList.push({ name: url })
        this.url = ''
        this.$nextTick(() => {
          this.urlList.forEach((item, index) => {
            this.$refs['del' + (index + 1)].$el.classList.value += ' ' + 'del' + (index + 1)
          })
        })
      } else {
        this.$messages.error(this.$t('请填写URL'))
      }
    },
    delUrl (data) {
      for (let index in this.urlList) {
        if (this.urlList[index].name === data.name) {
          this.urlList.splice(index, 1)
          break
        }
      }
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-switch {
  /deep/ .el-switch__core {
    &::before {
      content: "关";
      color: #fff;
      position: absolute;
      // font-size: 14px;
      transform: scale(0.85);
      left: 20px;
    }
  }

  &.switch-is-actived {
    /deep/ .el-switch__core {
      &::before {
        content: "开";
        left: 5px;
        transform: scale(0.85);
      }
    }
  }
}
</style>
